﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using log4net.Repository.Hierarchy;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace WebApi.Middlewares
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class PermissionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private readonly PermissionOptions _options;

        // 因为是默认使用依赖注入，IOptions是能够依赖注入的，而如果使用PermissionOptions作为形参，那么调用UsePermissionMiddleware的时候必须传入PermissionOptions对象
        // 否则会因为没有AddScoped导致无法进行注入，直接报错
        //public PermissionMiddleware(RequestDelegate next, PermissionOptions options, ILogger<PermissionMiddleware> logger) : this(next, logger)
        //{
        //    _options = options;
        //}

        public PermissionMiddleware(RequestDelegate next, IOptions<PermissionOptions> options, ILogger<PermissionMiddleware> logger) : this(next, logger)
        {
            _options = options.Value;
        }

        public PermissionMiddleware(RequestDelegate next, ILogger<PermissionMiddleware> logger) : this(next)
        {
            _logger = logger;
        }

        public PermissionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {

            await _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class PermissionMiddlewareExtensions
    {
        public static IApplicationBuilder UsePermissionMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<PermissionMiddleware>();
        }

        public static IApplicationBuilder UsePermissionMiddleware(this IApplicationBuilder builder, PermissionOptions options)
        {
            return builder.UseMiddleware<PermissionMiddleware>(options);
        }
    }

    public class PermissionOptions
    {

    }
}
